<script setup lang="ts">
import { ref } from 'vue'
import type { UniFormsRules, UniLoadMoreContentText, UniLoadMoreStatus } from '@uni-helper/uni-ui-types'
import { searchService, searchUserService } from '@/common/service/search'
import type { User } from '@/common/types/user'
import { createNotificationService } from '@/common/service/notification'
import type { CreateNotificationParam } from '@/common/types/request'
import { PageTitle } from '@/common/constants'

/** 通知类型 */
const notificationType = ref([
  {
    value: 0,
    text: '系统通知',
  },
  {
    value: 1,
    text: '任务通知',
  },

])

/** 表单信息 */
const notificationForm = ref<CreateNotificationParam>({
  content: '',
  notificationType: 0,
  receiverId: null,
})

/** 搜索后的用户数组列表 */
const userList = ref<Pick<User, 'id' | 'nickname' | 'avatarUrl'>[]>([])

const searchStatus = ref<UniLoadMoreStatus>('more')

/** 搜索加载显示的文本 */
const searchStatusText: UniLoadMoreContentText = {
  contentdown: '搜索查询用户',
  contentrefresh: '加载中',
  contentnomore: `没有昵称中包含该字段用户`,
}

/**
 * 搜索用户
 */
const onSearch = async (query: string) => {
  searchStatus.value = 'loading'

  const { data } = await searchUserService(query)

  const users = data as unknown as User[]

  if (users.length === 0) {
    userList.value = []
    return searchStatus.value = 'noMore'
  }

  userList.value = users.map((user) => {
    return {
      id: user.id,
      nickname: user.nickname,
      avatarUrl: user.avatarUrl,
    }
  })

  searchStatus.value = 'more'
}

/**
 * 选择用户
 */
const onSelectUser = (userId: number) => {
  console.log(userId)

  notificationForm.value.receiverId = userId
}

/** 表单通知ref */
const notificationFormRef = ref()

/** 表单通知 */
const formRules: UniFormsRules = {
  content: {
    rules: [
      {
        required: true,
        errorMessage: '请输入通知内容',
      },
      {
        maxLength: 2000,
        errorMessage: '通知字符长度不能大于{maxLength}',
      },
      {
        validateFunction: (rule, value, data, callback) => {
          if (value.length < 50) {
            callback('通知内容长度不能小于50')
          }
          return true
        },
      },
    ],
  },
  notificationType: {
    rules: [
      {
        required: true,
        errorMessage: '请选择通知类型',
      },
    ],
  },
}

/** 创建通知 */
const createNotification = () => {
  console.log(notificationForm.value)

  notificationFormRef.value.validate((err: any) => {
    if (err) {
      return showSimpleToast(FORM_VERIFY_FAIL)
    }

    createNotificationService(notificationForm.value).then(() => {
      showSimpleToast(CREATE_NOTIFICATION_SUCCESS)
    }).catch(() => {
      showSimpleToast(CREATE_NOTIFICATION_FAIL)
    }).finally(() => {
      goToSwitchTab(PagePath.HOME)
    })
  })
}
</script>

<template>
  <view class="message-create-container">
    <hope-nav-bar :title="PageTitle.CREATE_NOTIFICATION" is-back-icon />
    <view class="message-create-scroll-container">
      <scroll-view scroll-y class="message-create-scroll-content">
        <view class="message-create-form">
          <uni-forms
            ref="notificationFormRef" label-position="top" label-width="100%" :model="notificationForm"
            :rules="formRules"
          >
            <uni-forms-item required label="通知内容" name="content">
              <uni-easyinput v-model="notificationForm.content" trim type="textarea" placeholder="请输入通知内容" />
            </uni-forms-item>
            <uni-forms-item required label="通知类型" name="notificationType">
              <uni-data-checkbox
                v-model="notificationForm.notificationType" selected-color="#ED4556"
                selected-text-color="#333" :localdata="notificationType"
              />
            </uni-forms-item>
            <uni-forms-item label="指定发送用户" name="receiverId">
              <text class="sub">
                (可选,不指定用户时默认发送给所有用户)
              </text>
              <hope-search-bar type="search" placeholder-text="请输入您要搜索的用户" @on-search="onSearch" />
              <view class="user-list">
                <view
                  v-for="user in userList" :key="user.id" class="user-list-item" :class="{
                    'user-list-item-select': user.id === notificationForm.receiverId,
                  }" @click="() => onSelectUser(user.id)"
                >
                  <image :src="user.avatarUrl" mode="scaleToFill" class="avatar" />
                  <text class="nickname">
                    {{ user.nickname }}
                  </text>
                </view>
                <uni-load-more :status="searchStatus" :content-text="searchStatusText" />
              </view>
            </uni-forms-item>
          </uni-forms>
        </view>
      </scroll-view>
    </view>
    <view class="message-create-bottom" @click="createNotification">
      <hope-button title="创建通知" />
    </view>
  </view>
</template>

<style scoped lang="scss">
.message-create {
  &-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    overflow: hidden;
  }

  &-scroll {
    &-container {
      flex: 1;
      overflow: scroll;
    }

    &-content {
      height: 100%;
      background-color: $color-white;
    }
  }

  &-type {
    .radio-group {
      display: flex;
      gap: $padding-base;
    }

  }

  &-form {
    display: flex;
    flex-direction: column;
    gap: $padding-base;
    padding-top: $padding-base;
    padding-inline: $padding-base;

    &-item {
      .textarea {
        width: 100%
      }

    }
  }

  &-bottom {

    background-color: $color-white;
    padding-inline: $padding-base;
    padding-top: 16rpx;
    padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));

  }
}

.user-list {
  display: flex;
  flex-direction: column;
  margin-top: $padding-base;
  gap: $padding-base;

  &-item {
    display: flex;
    align-items: center;
    gap: $padding-base;
    padding: $padding-base;
    border-radius: $padding-base;
    background-color: $bg-gray;
    border: 1px solid $color-white;

    &-select {
      border: 1px solid $border-color;
      background-color: $color-white;
    }

    .avatar {
      width: 100rpx;
      height: 100rpx;
      border-radius: 50%;
    }

    .nickname {
      font-size: $font-size-base;
      color: $uni-text-color-grey;
    }
  }
}

.sub {
  font-size: $font-size-sm;
  color: $uni-text-color-grey;
}
</style>
